import os
from ipaddress import IPv4Address

import pandas as pd


class IpSearch(object):
    """
    created by chenhj at 2017/8/14

    """
    def __init__(self, filename):
        """
        created by chenhj at 2017/8/14

        """
        with open(filename, 'rb') as f:
            reader = pd.read_csv(
                f, delimiter='|', names=[
                    'ip_start', 'ip_end', 'num_start', 'num_end',
                    'land', 'country', 'prov', 'city', 'county', 'isp', 'code',
                    'english', 'cc', 'longitude', 'latitude']
            )
        self.reader = reader

    def find(self, ip):
        """
        created by chenhj at 2017/8/14
        返回一个列表[省份, 城市, 地区编码]
        """
        addr = IPv4Address(ip)
        values = self.reader[['prov', 'city', 'code', 'county']][
            (self.reader.num_end >= int(addr)) & (self.reader.num_start <= int(addr))
        ].values
        if values.any():
            return values[0]
        return []

ip_util = IpSearch(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ip.txt'))


if __name__ == '__main__':
    print(ip_util.find('115.153.95.251'))
    print(ip_util.find('123.125.71.38'))
    print(ip_util.find('183.15.178.208'))
